<template>
  <div class="password-strength">
    <span>密码强度：</span>
    <div class="strength-meter">
      <div
        v-for="(bar, index) in bars"
        :key="index"
        :style="{ width: bar.width + '%', backgroundColor: bar.color }"
        :class="{ 'bar-visible': bar.width > 0 }"
      ></div>
    </div>
    <span>{{ strengthText }}</span>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';

const props = defineProps({
  password: String,
  barWidth: {
    type: Number,
    default: 100,
  },
});

const strengthText = ref('无');
const bars = ref([
  { color: '#FF0000', width: 0 },
  { color: '#FFA500', width: 0 },
  { color: '#90EE90', width: 0 },
  { color: '#008000', width: 0 },
]);

// 密码强度计算函数
const calculateStrength = (password) => {
  if (password.length < 6) return 1; // 弱
  if (password.length < 8) return 2; // 一般
  if (password.length < 12) return 3; // 强
  return 4; // 非常强
};

watch(() => props.password, (newPassword) => {
  const strength = calculateStrength(newPassword);
  bars.value.forEach((bar, index) => {
    bar.width = (index < strength) ? (props.barWidth / 4) : 0;
  });
  switch (strength) {
    case 1:
      strengthText.value = '弱';
      break;
    case 2:
      strengthText.value = '一般';
      break;
    case 3:
      strengthText.value = '强';
      break;
    case 4:
      strengthText.value = '非常强';
      break;
  }
});
</script>

<style scoped>
.password-strength {
  display: flex;
  align-items: center;
}
.strength-meter {
  display: flex;
  gap: 4px;
  margin: 0 8px;
}
.strength-meter > div {
  height: 10px;
  transition: width 0.3s ease; /* 平滑过渡效果 */
}
.bar-visible {
  opacity: 1;
}
</style>
